import React, { useState, useEffect } from 'react'
import './index.modules.scss'
import SearchView from '@/components/searchView/index'
import { useNavigate } from 'react-router-dom'
import {
  Space,
  Table,
  Button,
  Modal,
  Card,
  message,
  Popconfirm,
  Pagination,
  Input,
  Form
} from 'antd'
import {
  carOwnerList,
  carOwnerAdd,
  carOwnerDelete,
  carOwnerchange,
  carOwnerSerach,
  carOwnerCreateExcel
} from '@/http/api/carOwner'
import dayjs from 'dayjs'
let pageData = {
  page: 1,
  size: 10,
  total: 0,
  appid: localStorage.getItem('appid')
}
let typeList = [
  {
    title: '车主名称',
    type: 'inpute',
    model: 'name'
  },
  {
    title: '联系方式',
    type: 'inpute',
    model: 'phone'
  },
  {
    title: '注册时间',
    type: 'date',
    model: 'create_time'
  }
]
let _id = ''
let selectedRowsdata = []
const App = () => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const Navigate = useNavigate()
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState([])
  const [isShowChange, setisShowChange] = useState(false)
  const columns = [
    {
      title: '注册时间',
      dataIndex: 'create_time',
      align: 'center',
      render: (create_time) => {
        return <div>{dayjs(create_time).format('YYYY-MM-DD HH:mm:ss')}</div>
      }
    },
    {
      title: '车主姓名',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '联系方式 ',
      dataIndex: 'phone',
      align: 'center'
    },
    {
      title: '密码',
      dataIndex: 'password',
      align: 'center'
    },
    {
      title: '质保信息',
      align: 'center',
      render: (data) => {
        return (
          <a
            onClick={() => {
              Navigate('/home/carOwnerQuality', {
                state: { id: data._id, name: data.name, phone: data.phone }
              })
            }}
          >
            {data.qualityNum}
          </a>
        )
      }
    },
    {
      title: '车险信息',
      align: 'center',
      render: (data) => {
        return (
          <a
            onClick={() => {
              Navigate('/home/carOwnerInsurance', {
                state: { id: data._id, name: data.name, phone: data.phone }
              })
            }}
          >
            {data.insuranceNum}
          </a>
        )
      }
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              setisShowChange(true)
              form.setFieldsValue(data)
              _id = data._id
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }

  // 获取列表
  const getList = async () => {
    const res = await carOwnerList(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }

  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 编辑
  const compileFn = async (data) => {
    let res = ''
    data.appid = localStorage.getItem('appid')
    if (_id) {
      data._id = _id
      res = await carOwnerchange(data)
    } else {
      res = await carOwnerAdd(data)
    }

    if (res.data.type == 1) {
      messageApi.success(res.data.message)
      setisShowChange(false)
      form.resetFields()
      getList()
    } else {
      messageApi.error(res.data.message)
    }
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await carOwnerDelete({ id: data._id })
    messageApi.success(res.data.message)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {
      id: 'all'
    }
    if (selectedRowsdata.length > 0) {
      data = {
        id: selectedRowsdata
      }
    }
    data.appid = localStorage.getItem('appid')
    const res = await carOwnerCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '车主信息.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  // 搜索
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      ...data
    }
    const res = await carOwnerSerach(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  return (
    <div>
      <Card>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div>
          <div className="headerButton">
            <Button
              style={{ marginRight: '10px' }}
              type="primary"
              onClick={() => {
                setisShowChange(true)
              }}
            >
              新增车主信息
            </Button>
            <Button
              type="primary"
              onClick={() => {
                exportExcel()
              }}
            >
              导出信息
            </Button>
          </div>
        </div>
        <Table
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
          pagination={false}
          bordered
          rowKey="key"
          columns={columns}
          dataSource={dataSource}
        />
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      {/* 编辑 */}
      <Modal
        open={isShowChange}
        footer={[]}
        onCancel={() => {
          setisShowChange(false)
          form.resetFields()
        }}
      >
        <Form
          name="basic"
          labelCol={{
            span: 5
          }}
          wrapperCol={{
            span: 13
          }}
          style={{
            maxWidth: 600
          }}
          initialValues={{
            remember: true
          }}
          onFinish={compileFn}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="车主名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入车主名称'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="账号"
            name="account"
            rules={[
              {
                required: true,
                message: '请输入账号'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="电话"
            name="phone"
            rules={[
              {
                required: true,
                message: '请输入电话'
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 0
            }}
          >
            <div className="footButtonS center">
              <Button className="cancelButton center" htmlType="submit">
                取消
              </Button>
              <Button className="confirmButton center" htmlType="submit">
                确定
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  )
}
export default App
